"""
@file:   user
@author: FrankYi
@date:   2020/08/12
@desc:
"""

from libs.bp import NestableBlueprint
from flask_restful import Api, Resource
from flask import request,g
from models.user import UserSouth
from forms.user import UserForm
from forms.login import LoginForm
from serializer.user import user_schema
from libs.response import genrate_response
from libs.statuscode import FormValidateException,ArgsTypeException
from libs.exceptionhandle import default_error_handler


user_bp = NestableBlueprint('user', __name__, url_prefix='/user')
api = Api(user_bp)

# api.handle_error = default_error_handler

class RegisterView(Resource):
    def post(self):
        data = request.json
        form = UserForm(data=data)
        if form.validate():
            # 创建用户
            UserSouth.create_user(useremail=data.get("email"),
                                  password=data.get("password"),
                                  username=data.get("username"))

            user = UserSouth.query.filter_by(useremail=data.get("email")).first()
            result = user_schema.dump(user)
            # 返回结果
            return genrate_response(data=result)
        else:
            result = form.errors
            raise FormValidateException(message=result)


class LoginView(Resource):
    def post(self):
        data = request.json
        if not data:
            raise ArgsTypeException('错误')
            # 检验合理性
        login_form = LoginForm(data=data)
        user = login_form.validate()
        result = user_schema.dump(user)
        return genrate_response(data=result)


api.add_resource(RegisterView, '/register/')
api.add_resource(LoginView, '/login/')